<template>
  <div class="user-management">
    <h1>用户管理</h1>
    
    <div class="admin-navigation">
      <el-button 
        type="primary" 
        @click="$router.push('/admin/users')"
        :plain="$route.path !== '/admin/users'"
      >
        用户管理
      </el-button>
      <el-button 
        type="primary" 
        @click="$router.push('/admin/anonymous-visits')"
        :plain="$route.path !== '/admin/anonymous-visits'"
      >
        匿名访问记录
      </el-button>
    </div>
    
    <el-table :data="users" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" width="180" />
      <el-table-column prop="phone" label="手机号" width="180" />
      <el-table-column prop="role" label="角色" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'info'">
            {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="注册时间" width="200" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(scope.row)"
            :disabled="currentUser.id === scope.row.id"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" title="编辑用户" width="500px">
      <el-form :model="currentUser" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="currentUser.username" disabled />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="currentUser.phone" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="currentUser.role" placeholder="请选择角色">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElTable, ElTableColumn, ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElTag, ElMessage, ElMessageBox } from 'element-plus'
import http from '@/utils/http'

export default {
  name: 'UserManagement',
  components: {
    ElTable,
    ElTableColumn,
    ElButton,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElSelect,
    ElOption,
    ElTag
  },
  data() {
    return {
      users: [],
      loading: false,
      dialogVisible: false,
      currentUser: {
        id: null,
        username: '',
        phone: '',
        role: 'user'
      }
    }
  },
  mounted() {
    this.loadUsers()
  },
  methods: {
    async loadUsers() {
      this.loading = true
      try {
        const response = await http.get('/users')
        this.users = response.users
      } catch (error) {
        ElMessage.error('加载用户列表失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.loading = false
      }
    },
    
    handleEdit(user) {
      this.currentUser = { ...user }
      this.dialogVisible = true
    },
    
    handleDelete(user) {
      ElMessageBox.confirm(
        `确定要删除用户 "${user.username}" 吗？此操作无法撤销。`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          await http.delete(`/users/${user.id}`)
          ElMessage.success('用户删除成功')
          this.loadUsers() // Refresh the user list
        } catch (error) {
          ElMessage.error('删除用户失败: ' + (error.response?.data?.message || error.message))
        }
      }).catch(() => {
        // Cancelled
      })
    },
    
    saveUser() {
      // Save the user changes
      http.put(`/users/${this.currentUser.id}`, this.currentUser)
        .then(response => {
          ElMessage.success('用户信息更新成功')
          this.dialogVisible = false
          this.loadUsers() // Refresh the user list
        })
        .catch(error => {
          ElMessage.error('更新用户信息失败: ' + (error.response?.data?.message || error.message))
        })
    }
  }
}
</script>

<style scoped lang="scss">
.user-management {
  padding: 0 20px;
  h1 {
    margin-top: 0;
  }
}

.admin-navigation {
  margin-bottom: 20px;
}

.admin-navigation .el-button {
  margin-right: 10px;
}
</style>